package com.linkin.homepage.base;

import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;

import com.linkin.homepage.base.util.ScreenUtils;
import com.linkin.homepage.base.viewmapping.ViewMapUtil;

public abstract class BaseDialogFragment extends DialogFragment {

    private int mDialogHeight = 0;
    protected Context mContext;
    private boolean mFragmentDestroyed = true;
    private DialogInterface.OnDismissListener mOnDismissListener;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    public void setOnDismissListener(DialogInterface.OnDismissListener dismissListener) {
        mOnDismissListener = dismissListener;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mFragmentDestroyed = false;
        View view = ViewMapUtil.inflate(this, inflater, container);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    @Override
    public void onStart() {
        super.onStart();
        //设置Dialog的宽高
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setGravity(Gravity.BOTTOM);
            window.setLayout(ScreenUtils.getScreenWidth(getContext()), mDialogHeight);
        }
    }

    public void setDialogHeight(int dialogHeight) {
        this.mDialogHeight = dialogHeight;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        if (mOnDismissListener != null) {
            mOnDismissListener.onDismiss(dialog);
        }
    }

    @Override
    public void onDestroyView() {
        mFragmentDestroyed = true;
        clear();
        super.onDestroyView();
    }

    public boolean isAlive() {
        return isFragmentAlive();
    }

    public boolean isFragmentAlive() {
        return !isFragmentDestroyed();
    }

    public boolean isFragmentDestroyed() {
        return mFragmentDestroyed;
    }

    protected abstract void initView();

    protected void initData() {
    }

    protected abstract void clear();


}
